package com.cea.papyrus.core.editor;

import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;

/**
 * 
 * This class is used to give access to Papyrus CommandStack
 * CommandStack can be force with a particular stack instead of 
 * using default command stack. This is maily used when Papyrus is
 * used from an external tool. In such a case the getDefaultCommandStack
 * method is usuallly inefficient to retrieve correct stack because
 * Papyrus is not necessarilly the active editor.
 *
 */
public class CommandStackUtils {

	/**
	 * Property used to force CommandStack when default is null
	 */
	private static org.eclipse.gef.commands.CommandStack stack;
		
	/**
	 * If default CommandStack is not null it is returned, else
	 * a forced CommandStack may be used.
	 * @return
	 */
	public static org.eclipse.gef.commands.CommandStack getCommandStack() {
		if (getDefaultCommandStack() != null) {
			stack = getDefaultCommandStack();
		}
		return stack;
	}

	/**
	 * Force stack property with a parameter
	 */
	public static void forceCommandStack(org.eclipse.gef.commands.CommandStack newStack) {
		stack = newStack;
	}
	
	/**
	 * Gets the default CommandStack for the currently active editor
	 * This method was formerly in LookForElement utility class.
	 * 
	 * @return the command stack
	 */
	private static org.eclipse.gef.commands.CommandStack getDefaultCommandStack(){

		IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		if ((activePage !=null)
				&& (activePage.getActiveEditor() != null)) {

			IEditorPart editorPart = activePage.getActiveEditor();
			
			if (editorPart instanceof MultiDiagramEditor) {
				IEditorPart multiEditorPart;
				multiEditorPart = ((MultiDiagramEditor)editorPart).getActiveEditor();
				org.eclipse.gef.commands.CommandStack stack = 
					(org.eclipse.gef.commands.CommandStack) multiEditorPart.getAdapter(org.eclipse.gef.commands.CommandStack.class);
				return stack;
			} else {
				return (org.eclipse.gef.commands.CommandStack) editorPart.getAdapter(org.eclipse.gef.commands.CommandStack.class);
			}
		}
		return null;
	}
}
